package com.bls.cate.service;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.bls.cate.constant.IntentCode;
import com.bls.cate.constant.Keys;
import com.bls.cate.model.AttentionListRes;
import com.bls.cate.model.LoginSpRes;
import com.bls.cate.ui.activity.write_article.PublishImageItem;
import com.bls.cate.ui.activity.write_article.WriteArticleActivity;
import com.bls.cate.utils.AccountUtil;
import com.bls.cate.utils.ImageUtil;
import com.bls.cate.utils.TxObjectStorage;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.CosXmlResultListener;
import com.tencent.cos.xml.model.object.PutObjectRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 　　  () 　　　  ()
 * 　　  ( ) 　　　( )
 * 　　  ( ) 　　　( )
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　┻　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ——————————————————
 * Created by BinglingSu on 2018/2/7.
 */

public class UploadArticleImageService extends IntentService {

    private String publishName;
    private ArrayList<PublishImageItem> pathList;
    private CosXmlService cosXmlService;
    private String title;
    private List<AttentionListRes.ResultListDataBean> beanList;
    private LoginSpRes loginSpRes;

    private int imageUploadNum;  //需要上传图片的数量
    private int imageUploadOverIndex = 0; //上传完成的图片标记

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public UploadArticleImageService() {
        super("UploadArticleImageService");
        beanList = new ArrayList<>();

    }


    @Override
    @SuppressWarnings("unchecked")
    protected void onHandleIntent(@Nullable Intent intent) {
        assert intent != null;
        loginSpRes = AccountUtil.getStrLoginSp();
        cosXmlService = new TxObjectStorage().getCosXmlService(getApplicationContext());

        publishName = intent.getStringExtra(IntentCode.PublishArticle.PUBLISH_NAME);
        title = intent.getStringExtra(IntentCode.PublishArticle.PUBLISH_TITLE);
        pathList = (ArrayList<PublishImageItem>) intent.getSerializableExtra(IntentCode.PublishArticle.PUBLISH_IMAGE_LIST);

        imageUploadNum = pathList.size();
        for (int i = 0; i < imageUploadNum; i++) {
            final int[] wh = ImageUtil.getImageWidthHeight(pathList.get(i).getImagePath());
            pathList.get(i).setImageWidth(String.valueOf(wh[0]));
            pathList.get(i).setImageHeight(String.valueOf(wh[1]));
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    upLoadArticleImage(finalI);
                }
            }).start();
        }



/*            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkGo.<String>get(Interface.INTERFACE_ATTENTION).params("RequestMethod", "AttentionList").params("UniqueId", loginSpRes.getUniqueId()).execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            AttentionListRes res = new Gson().fromJson(response.body(), AttentionListRes.class);
                            if (!res.isResultStatus())
                                return;
                            beanList = res.getResultListData();
                            if (null == beanList || beanList.isEmpty())
                                return;
                            for (AttentionListRes.ResultListDataBean bean : beanList) {
                                OkGo.<String>get(Interface.INTERFACE_XMSERVICE)
                                        .params("RequestMethod", "XMPushToAccount")
                                        .params("PushId", loginSpRes.getUniqueId())
                                        .params("NickName", loginSpRes.getNickName())
                                        .params("Content", "《" + title + "》")
                                        .params("NotifyId", "1")
                                        .params("OtherPushId", bean.getOtherUniqueId())
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(Response<String> response) {

                                            }
                                        });
                            }
                        }
                    });
                }
            }).start();*/

    }

/*    public void compressImage(final int current) {
        final String imagePath = pathList.get(current);
        Luban.with(getApplicationContext()).setTargetDir(getPath()).load(imagePath).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                upLoadHeader(file.getAbsolutePath(), current);
            }

            @Override
            public void onError(Throwable e) {
                upLoadHeader(imagePath, current);

            }
        }).launch();
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Cate/images/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }*/


    private void upLoadArticleImage(final int index) {
        String cosPath = "/article_image/".concat(publishName).concat("_").concat(pathList.get(index).getImageIndex()).concat(".png"); //格式如 cosPath = "/test.txt";
        PutObjectRequest putObjectRequest = new PutObjectRequest(Keys.TX_OBJECT_STORAGE.TX_OBJECT_STORAGE_BUCKET, cosPath, pathList.get(index).getImagePath());
        putObjectRequest.setSign(6000, null, null);
        cosXmlService.putObjectAsync(putObjectRequest, new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                LogUtils.i("CosXmlService", "onSuccess");
                pathList.get(index).setImagePath(result.accessUrl);
                pathList.get(index).setUploadImage(true);
                imageUploadOverIndex = imageUploadOverIndex + 1;
                checkUploadImageResult(imageUploadOverIndex);
            }

            @Override
            public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                String errorMsg = clientException != null ? clientException.toString() : serviceException.toString();
                LogUtils.i("CosXmlService", errorMsg);
                imageUploadOverIndex = imageUploadOverIndex + 1;
                checkUploadImageResult(imageUploadOverIndex);
            }
        });
    }


    /**
     * 检查上传图片的结果
     *
     * @param imageUploadOverIndex
     */
    private void checkUploadImageResult(int imageUploadOverIndex) {
        if (imageUploadOverIndex != imageUploadNum)
            return;
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        ArrayList<PublishImageItem> resultList = new ArrayList<>();
        for (int i = 0; i < imageUploadNum; i++) {
            if (pathList.get(i).isUploadImage()) {
                jsonArray.add(pathList.get(i));
            }
        }
        String jsonArrayString = jsonArray.toJSONString();
        LogUtils.i("jsonArrayString", jsonArrayString);
        jsonObject.put("ImagesInfo", jsonArray.toJSONString());
        String jsonImages = jsonObject.toJSONString();

        LogUtils.i("jsonImages", jsonImages);

        Intent intent = new Intent(WriteArticleActivity.SERVICE_RECEIVER);
        intent.putExtra(IntentCode.PublishArticle.UPLOAD_IMAGE_RESULT, "111");
        getApplicationContext().sendBroadcast(intent);

        /*OkGo.<String>get(Interface.INTERFACE_ARTICLE).tag(this).cacheMode(CacheMode.NO_CACHE)
                .params("RequestMethod", "AddArticleImage")
                .params("Code", publishName)
                .params("Path", result.accessUrl)
                .params("Width", String.valueOf(wh[0]))
                .params("Height", String.valueOf(wh[1]))
                .params("ImageIndex", String.valueOf(current))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("INTERFACE_ARTICLE", response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });*/

        OkGo.<String>post("http://172.18.0.69:8080/Cate/Article/ArticlePublish").params("publishName", publishName).params("title", title)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }
}
